﻿using System.Text.RegularExpressions;
using FluentParser.Expressions;

namespace FluentParser.Expressions.Terminals.Parsing
{
    /// <summary>
    /// Symbol reading a value from a regular expression.
    /// </summary>
    /// <example><code>
    /// Symbol number = ParseSymbol.Regex("[0-9]+");
    /// 
    /// number.Parse("SomeText") --> failure
    /// number.Parse("1234")     --> 1234
    /// </code></example>
    public class ParseRegexSymbolTerminal : Symbol
    {
        public Regex Regex { get; private set; }

        public ParseRegexSymbolTerminal(string regexExpression)
        {
            Regex = new Regex("\\G" + regexExpression, RegexOptions.Compiled);
            TypeOperation = OperationType.Parsing;
        }

        public ParseRegexSymbolTerminal(Regex regex)
        {
            Regex = regex;
            TypeOperation = OperationType.Parsing;
        }

        public override ParsingResult<object> Parse(GrammarContext context, int index)
        {
            Match match = Regex.Match(context.Text, index);
            if (match.Success)
                return new ParsingResult<object>(index, match.Length, match.Value);

            return null;
        }

        public override void ParseNode(GrammarContext context, ParsingNodeResult node)
        {
            Match match = Regex.Match(context.Text, node.Index);
            if (match.Success)
            {
                node.Value = match.Value;
                node.IsSuccess = true;
                node.Length = match.Length;
                node.ExploredLength = match.Length;
            }
        }
    }
}